//
//  LoversViewController.m
//  Emoticon
//
//  Created by ytkjs2 on 2020/3/26.
//  Copyright © 2020 ytk. All rights reserved.
//

#import "LoversViewController.h"
#import "LoverViewCell.h"
#import <Photos/Photos.h>

@interface LoversViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong)NSMutableArray * dataSource;

@property (nonatomic, assign)int page;

@end

@implementation LoversViewController

- (NSMutableArray *)dataSource
{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.title = @"情侣套图";
    
    __weak typeof(self)weakSelf = self;
    
    _tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.dataSource = [NSMutableArray array];
        
        weakSelf.page = 1;
        
        [PictureData getRequestWithServiceUrl:LOVER_URL parameters:@{@"page":@(weakSelf.page)} success:^(id  _Nonnull responseObject) {
            
            NSArray * arr = [responseObject objectForKey:@"data"];
            
            for (NSDictionary * dic in arr) {
                LoverPicModel * model = [LoverPicModel mj_objectWithKeyValues:dic];
                [weakSelf.dataSource addObject:model];
            }
            
            [weakSelf.tableview reloadData];
            [weakSelf.tableview.mj_header endRefreshing];
            
        } failure:^(NSError * _Nonnull error) {
            [weakSelf.tableview.mj_header endRefreshing];
        }];
    }];
    
    [_tableview.mj_header beginRefreshing];
    
    _tableview.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        
        weakSelf.page ++;
        
        [PictureData getRequestWithServiceUrl:LOVER_URL parameters:@{@"page":@(weakSelf.page)} success:^(id  _Nonnull responseObject) {
            
            NSArray * arr = [responseObject objectForKey:@"data"];
            
            for (NSDictionary * dic in arr) {
                LoverPicModel * model = [LoverPicModel mj_objectWithKeyValues:dic];
                [weakSelf.dataSource addObject:model];
            }
            
            [weakSelf.tableview reloadData];
            [weakSelf.tableview.mj_footer endRefreshing];
            
        } failure:^(NSError * _Nonnull error) {
            [weakSelf.tableview.mj_footer endRefreshing];
        }];
        
    }];
    
    [_tableview.mj_footer beginRefreshing];
    
}

#pragma mark <UITableViewDataSource>

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat width = (rScreenWidth - 27)/2;
    return width * rScreenHeight/rScreenWidth + 9;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 45;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 15;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, rScreenWidth, 45)];
    view.backgroundColor = [UIColor clearColor];
    
    UIView * cornerView = [[UIView alloc]initWithFrame:CGRectMake(0, 5, rScreenWidth, 40)];
    cornerView.backgroundColor = [UIColor whiteColor];
    [self setViewCornerRadius:cornerView isHead:YES];
    [view addSubview:cornerView];
    
    LoverPicModel * model = _dataSource[section];
    UILabel * lab = [[UILabel alloc]initWithFrame:CGRectMake(15, 10, 200, 20)];
    lab.text = model.title;
    lab.font = [UIFont boldSystemFontOfSize:14];
    [cornerView addSubview:lab];
    
    return view;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, rScreenWidth, 15)];
    view.backgroundColor = [UIColor clearColor];
    
    UIView * cornerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, rScreenWidth, 10)];
    cornerView.backgroundColor = [UIColor whiteColor];
    [self setViewCornerRadius:cornerView isHead:NO];
    [view addSubview:cornerView];
    
    return view;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LoverViewCell * cell = [[NSBundle mainBundle]loadNibNamed:@"LoverViewCell" owner:nil options:nil][0];
    cell.controller = self;
    LoverPicModel * model = _dataSource[indexPath.section];
    [cell setBtnWithImage:model.image withTag:indexPath.section];
    return cell;
}

-(void)btnAction:(UIButton *)btn
{
    NSLog(@"%ld",btn.tag);
    NSInteger section = btn.tag/2;
    NSInteger index = btn.tag%2;
    LoverPicModel * model = _dataSource[section];
    DownloadViewController * downloadVC = [[DownloadViewController alloc]initWithNibName:@"DownloadViewController" bundle:nil];
//    downloadVC.picType = 3;
    downloadVC.isLongPic = YES;
    downloadVC.dataSource = [NSMutableArray arrayWithObjects:model, nil];
    downloadVC.picIndex = index;
    downloadVC.isLoverVc = YES;
    downloadVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:downloadVC animated:YES];
}

//-(void)btn2Action:(UIButton *)btn
//{
//    NSLog(@"%ld",btn.tag);
//}

-(void)downloadAction:(UIButton *)btn
{
    NSLog(@"%ld",btn.tag);
    LoverPicModel * model = _dataSource[btn.tag];
    NSArray * imgArr = [model.image copy];
    for (NSString * imgStr in imgArr) {
        NSURL *imgUrl = [NSURL URLWithString:imgStr];
        NSData *data = [NSData dataWithContentsOfURL:imgUrl];
        UIImage *img = [UIImage imageWithData:data];
        
        NSString * localIdentifier = [[NSUserDefaults standardUserDefaults]objectForKey:imgStr];
        
        if (localIdentifier == nil) {
            [self execSavePhoto:img withUrl:imgStr];
        }
        else
        {
            PHAsset * asset = [PHAsset fetchAssetsWithLocalIdentifiers:@[localIdentifier] options:nil].firstObject;
            if (asset == nil) {
                [self execSavePhoto:img withUrl:imgStr];
            }
            else
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [MBProgressHUD showMessage:@"图片已存在"];
                    NSLog(@"图片已存在");
                });
            }
        }
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat sectionHeaderHeight = 45;//这里是我的headerView和footerView的高度
    if (scrollView.contentOffset.y<=sectionHeaderHeight&& scrollView.contentOffset.y>=0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    } else if(scrollView.contentOffset.y>=sectionHeaderHeight)
    {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
    
}


-(void)setViewCornerRadius:(UIView *)view isHead:(BOOL)isHead
{
    UIBezierPath *maskPath;
    if (isHead)
        maskPath= [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(10, 10)];
    else
        maskPath= [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(10, 10)];
    
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = view.bounds;
    maskLayer.path = maskPath.CGPath;
    view.layer.mask = maskLayer;
}

- (void)execSavePhoto:(UIImage *)image withUrl:(NSString *)urlStr{
    
    
  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    ////异步加载耗时操作
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlStr]];
    
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
    [[PHAssetCreationRequest creationRequestForAsset] addResourceWithType:PHAssetResourceTypePhoto data:data options:nil];
    }completionHandler:^(BOOL success,NSError*_Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
                    if(success && !error){
                        [MBProgressHUD showNormalMessage:@"保存成功"];;
        
                    }else
                        [MBProgressHUD showNormalMessage:@"保存错误"];;
        
                });
          }];
    });

}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
